<?php

namespace App\Http\Controllers\Api;

use App\Models\Area;
use App\Models\BackOrder;
use App\Models\BackOrderItem;
use App\Models\SellOrder;
use App\Models\SellOrderItem;
use App\Models\User;
use App\Models\UserAddress;
use Illuminate\Http\Request;

class BackOrderController extends BaseController
{
    public function feePrice(Request $request)
    {
        $address_id         = intval($request->get('address_id'));
        $sell_order_id      = intval($request->get('sell_order_id'));
        $back_book_num      = intval($request->get('back_book_num'));

        if(empty($sell_order_id) || empty($address_id))
        {
            return $this->err(1,200,'','参数错误');
        }


        $back_fee_price = $this->_fee_price($address_id,$back_book_num);
        $result = [
            'back_fee_price'    =>  $back_fee_price,
            'back_book_num'     =>  $back_book_num,
        ];
        return $this->ok($result);
    }

    /**
     * 计算退回运费
     * @param $address_id
     * @param $back_book_num
     * @return float|int
     */
    private function _fee_price($address_id, $back_book_num)
    {
        $address = UserAddress::query()->where('id',$address_id)->where('user_id',$this->user_id)->first();

        $province = Area::query()->where('id',$address->province_id)->first();
        $is_far = 0;
        if(!empty($province) && $province->is_far == 1)
        {
            //偏远地区
            $is_far = 1;
        }


        if($is_far)
        {
            //偏远地区
            $base_price = 22;
        }
        else
        {
            //非偏远地区
            $base_price = 7;
        }

        $back_fee_price = 0;
        if($back_book_num)
        {
            if($back_book_num <= 3)
            {
                $back_fee_price = $base_price;
            }
            else
            {
                $back_fee_price = $base_price + ceil(($back_book_num-3)/2)*3;
            }
        }

        return $back_fee_price;
    }


    public function submit(Request $request)
    {
        $address_id         = intval($request->get('address_id'));
        $sell_order_id      = intval($request->get('sell_order_id'));

        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $sell_order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($sell_order) || $sell_order->state != 5)
        {
            return $this->err(1,200,'','无法操作');
        }

        $back_book_num = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->where('state',2)->where('first_check_state',1)->count();
        if($back_book_num <= 0)
        {
            return $this->err(1,200,'','无法操作');
        }

        if($sell_order->can_back)
        {
            return $this->err(1,200,'','已超过3天无法取回');
        }

        $back_order = BackOrder::query()->where('user_id',$this->user_id)->where('sell_order_id',$sell_order_id)->where('state','>',0)->first();
        if(!empty($back_order))
        {
            return $this->err(1,200,'','无法重复下单');
        }

        if(!empty($address_id))
        {
            $address = UserAddress::query()->where('id',$address_id)->where('user_id',$this->user_id)->first();
        }
        else
        {
            $address = UserAddress::query()->where('deleted',0)->where('user_id',$this->user_id)->where('is_default',1)->first();
        }

        //计算回退运费
        $back_fee_price = 0;
        /*if($back_book_num)
        {
            if($back_book_num <= 3)
            {
                $back_fee_price = 7;
            }
            else
            {
                $back_fee_price = 7 + ceil(($back_book_num-3)/2)*2;
            }
        }*/

        $items = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->where('state',2)->where('first_check_state',1)->get();
        $books = [];
        if(!empty($items))
        {
            foreach ($items as $v)
            {
                $books[] = [
                    'book_id'       => $v->book_id,
                    'book_title'    => $v->book_title,
                    'book_image'    => $v->book_image,
                    'book_author'   => $v->book_author,
                    'state'         => $v->state,
                    'reason'        => $v->reason,
                ];
            }
        }


        $result = [
            'address'           =>  $address ? $address : (object)null,
            'back_fee_price'    =>  $back_fee_price,
            'back_book_num'     =>  $back_book_num,
            'books'             =>  $books,
        ];
        return $this->ok($result);
    }

    public function store(Request $request)
    {
        $address_id         = intval($request->get('address_id'));
        $sell_order_id      = intval($request->get('sell_order_id'));
        $book_ids           = trim($request->get('book_ids'));  //1,2,3

        if(empty($address_id) || empty($sell_order_id) || empty($book_ids))
        {
            return $this->err(1,200,'','参数错误');
        }

        $book_ids_arr = explode(',',$book_ids);

        $address = UserAddress::query()->where('id',$address_id)->first();
        if(empty($address) || $address->user_id != $this->user_id || $address->deleted)
        {
            return $this->err(1,200,'','收货地址有误');
        }

        $sell_order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($sell_order) || $sell_order->state != 5)
        {
            return $this->err(1,200,'','无法操作');
        }

        //$back_book_num = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->where('state',2)->where('first_check_state',1)->count();
        $back_book_num = count($book_ids_arr);
        if($back_book_num <= 0)
        {
            return $this->err(1,200,'','无法操作');
        }

        if($sell_order->can_back)
        {
            return $this->err(1,200,'','已超过3天无法取回');
        }

        $back_order = BackOrder::query()->where('user_id',$this->user_id)->where('sell_order_id',$sell_order_id)->where('state','>',0)->first();
        if(!empty($back_order))
        {
            return $this->err(1,200,'','无法重复下单');
        }

        //计算回退运费
        $back_fee_price = $this->_fee_price($address_id,$back_book_num);
        /*if($back_book_num)
        {
            if($back_book_num <= 3)
            {
                $back_fee_price = 7;
            }
            else
            {
                $back_fee_price = 7 + ceil(($back_book_num-3)/2)*2;
            }
        }*/

        $user = User::query()->where('id',$this->user_id)->first();
        \DB::beginTransaction();    //主事务
        try {
            $order = new BackOrder([
                'sell_order_id'         => $sell_order_id,
                'fee_price'             => $back_fee_price,
                'pay_type'              => 2,
                'created_at'            => $this->time,
                'updated_at'            => $this->time,
                'state'                 => 0,
                'address_id'            => $address_id,
                'address_receiver'      => $address->receiver,
                'address_mobile'        => $address->mobile,
                'address_province_name' => $address->province_name,
                'address_city_name'     => $address->city_name,
                'address_area_name'     => $address->area_name,
                'address'               => $address->address,
                'amount'                => $back_book_num,
                'express_delivery_id'   => 'ZTO',
                'user_openid'           => $user->wechat_openid,
            ]);
            // 订单关联到当前用户
            $order->user()->associate($user);
            // 写入数据库
            $order->save();


            $items = SellOrderItem::query()->where('sell_order_id',$sell_order_id)->where('state',2)->where('first_check_state',1)->get();
            foreach ($items as $v)
            {
                if(in_array($v->book_id,$book_ids_arr))
                {
                    BackOrderItem::create([
                        'back_order_id'         => $order->id,
                        'user_id'               => $order->user_id,
                        'book_id'               => $v->book_id,
                        'sell_order_item_id'    => $v->id,
                    ]);
                }
            }

            $result = (object) null;
            if($back_fee_price > 0)
            {
                /*$result = app('wechat_pay')->scan([
                'out_trade_no' => 'B'.$order->no,  // 商户订单流水号，与支付宝 out_trade_no 一样
                //'total_fee'    => $order->fee_price * 100, // 与支付宝不同，微信支付的金额单位是分。
                'total_fee'    => 0.01 * 100, // 与支付宝不同，微信支付的金额单位是分。
                'body' => '支付退回订单运费', // 订单描述
            ]);*/
                //正式环境小程序支付
                $wechat_order = [
                    'out_trade_no' => 'B'.$order->no,
                    'total_fee'    => $back_fee_price*100, // **单位：分**
                    //'total_fee' => 0.01*100, // **单位：分**
                    'body' => '支付退回订单运费',
                    //'openid' => 'oykEg5WGTi181uPuJUX5jT7jlvr4',
                    'openid' => $user->wechat_openid,
                ];

                $result = app('wechat_pay')->miniapp($wechat_order);
            }
            else
            {
                $order->update(['state' => 1]);
            }

            \DB::commit();
            return $this->res([
                'data' => [
                    'pay_info'  => $result,
                    'order_id'  => $order->id,
                    'order_no'  => $order->no,
                ]
            ]);
        } catch (\Exception $e) {
            \DB::rollBack();
            //echo $e->getMessage();
            return $this->err(1,200,$e->getMessage(),'下单失败');
        }
    }

    public function show(Request $request)
    {
        $back_order_id      = intval($request->get('back_order_id'));

        if(empty($back_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $back_order = BackOrder::query()->where('id',$back_order_id)->first();
        if(empty($back_order) || $back_order->user_id != $this->user_id)
        {
            return $this->err(1,200,'','订单不存在');
        }

        $back_items = BackOrderItem::query()->where('back_order_id',$back_order_id)->get();
        $book_ids = [];
        if($back_items->isNotEmpty())
        {
            foreach ($back_items as $v)
            {
                $book_ids[] = $v->book_id;
            }
        }


        $items = SellOrderItem::query()->where('sell_order_id',$back_order->sell_order_id)->where('state',2)->get();
        $books = [];
        foreach ($items as $v)
        {
            if(in_array($v->book_id,$book_ids))
            {
                $books[] = [
                    'book_id'               => $v->book_id,
                    'book_title'            => $v->book_title,
                    'book_author'           => $v->book_author,
                    'book_image'            => $v->book_image,
                    'reason'                => $v->reason,
                ];
            }

        }

        $result = [
            'id'                    => $back_order->id,
            'sell_order_id'         => $back_order->sell_order_id,
            'user_id'               => $back_order->user_id,
            'no'                    => $back_order->no,
            'fee_price'             => $back_order->fee_price,
            'pay_type'              => $back_order->pay_type,
            'pay_at'                => $back_order->pay_at,
            'express_no'            => $back_order->express_no,
            'express_delivery_id'   => $back_order->express_delivery_id,
            'created_at'            => $back_order->created_at,
            'state'                 => $back_order->state,
            'address_receiver'      => $back_order->address_receiver,
            'address_mobile'        => $back_order->address_mobile,
            'address_province_name' => $back_order->address_province_name,
            'address_city_name'     => $back_order->address_city_name,
            'address_area_name'     => $back_order->address_area_name,
            'address'               => $back_order->address,
            'amount'                => $back_order->amount,
            'books'                 => $books,
        ];
        return $this->ok($result);
    }
}
